<template>
  <el-drawer
    modal-class="merak_modal"
    v-model="drawerTariffCom"
    direction="rtl"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    size="600"
    :before-close="drawerClose"
  >
    <template #header>
      <div class="merak_modal_title">{{$t('goods_tariff.add_tariff')}}</div>
    </template>
    <div style="min-height: 200px" v-loading="tariffLoading">
      <el-form :model="tariffForm" ref="tariffRef" :rules="tariffRules" label-position="top">
        <el-row :gutter="40">
          <el-col :span="12" v-for="(formItem, formIndex) in formData" :key="formIndex">
            <el-form-item :label="formItem.name" :prop="formItem.key" v-if="formItem.type == 'input'">
              <el-input class="qf_input" v-model="tariffForm[formItem.key]" />
            </el-form-item>
            <el-form-item :label="formItem.name" :prop="formItem.key" v-if="formItem.type == 'number'">
              <el-input class="qf_input" v-model="tariffForm[formItem.key]" @input="val => formatChecks(val, formItem.key)" />
            </el-form-item>
            <el-form-item :label="formItem.name" :prop="formItem.key" v-if="formItem.type == 'select'">
              <el-select
                class="qf_select"
                style="width: 100%"
                filterable
                v-model="tariffForm[formItem.key]"
                @change="val => validKeys(val, formItem.key)"
              >
                <el-option v-for="cItem in formItem.values" :key="cItem.value" :label="cItem.label" :value="cItem.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-button type="default" @click="drawerClose">{{ $t("merak.cancel") }}</el-button>
      <el-button v-if="editNum == 'add'" type="primary" plain :loading="loadingState" @click="saveContinue('2', tariffRef)">{{
        $t("merak.save_continue")
      }}</el-button>
      <el-button type="primary" @click="submitForm('1', tariffRef)" :loading="loadingState">{{ $t("merak.save") }}</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, getCurrentInstance, nextTick } from "vue";
import { getTariffFormApi, getTariffSaveApi } from "@/api/modules/goodsArchive/tariff/tariff";
import { formatObj } from "./tariffFormat"; //格式校验
import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

import { ResultEnum } from "@/enums/httpEnum";
import { json } from "stream/consumers";

const { proxy } = getCurrentInstance();

const props = withDefaults(
  defineProps<{
    drawerTariff?: boolean;
    typeId: string;
    editId: string | number;
    editNum: string; //add新增 edit编辑
  }>(),
  {}
);

console.log(props);
//弹窗
const tariffLoading = ref(false);
const drawerTariffCom = ref(false);
watch(
  () => props.drawerTariff,
  newValue => {
    drawerTariffCom.value = newValue;
    console.log(drawerTariffCom.value);
    console.log(props.typeId);
    if (newValue) {
      //为真
      tariffLoading.value = true;
      initForm();
    }
  }
);
//关闭
const drawerClose = () => {
  $emit("drawerClose");
};
//loading加载
const loadingState = ref(false);

//#region form表单
const tariffRef = ref(null);
const tariffForm = ref({});
const tariffRules = ref({});
const formData = ref([]); //form表单整体数据

//保存并添加
const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
  submitForm(typebtn, formEl);
};
//保存

const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
  getTypeRequire("submit");
  setTimeout(() => {
    submitPost(typebtn, formEl);
  }, 100);
};

const submitPost = async (typebtn: string, formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      //保存
      loadingState.value = true;
      console.log(props.editNum)
      let saveParams = {
        ...tariffForm.value,
        type_id: props.typeId,
        id: props.editNum=='edit'?props.editId:''
      };
      getTariffSaveApi(saveParams).then(res => {
        // 	console.log(res);
        loadingState.value = false;
        if (res.code == ResultEnum.SUCCESS) {
          // 		getAlltree();//初始化组织架构
          successMsg(proxy.$t("merak.action_success"));
          $emit("saveSuccess");

          if (typebtn == 1) {
            $emit("drawerClose");
          }

          nextTick(() => {
            formEl.resetFields();
          });

          // 		tableRef.value?.reloadData();
          return;
        } else {
          failMsg(res.message);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//格式校验
let validObjs = {
  hs_code: [{ type: "push", key: "hs_code", msgRules: { min: 10, max: 10, message:proxy.$t('goods_tariff.verify_tariff_code'), trigger: "blur" } }],

  hs_code_cn: [
    { type: "append", key: "hs_code_cn", msgRules: { min: 10, max: 10, message: proxy.$t('goods_tariff.verify_tariff_code'), trigger: "blur" } }
  ],
  comparison_heel_height: [{ type: "append", key: "cc_heel_height" }],
  comparison_shoe_size: [{ type: "append", key: "shoe_size" }],
  comparison_weight: [{ type: "append", key: "cc_sku_net_weight" }],
  comparison_length: [{ type: "append", key: "cc_clothing_length" }],
  comparison_height: [{ type: "append", key: "cc_height" }],
  comparison_chest_circumference: [{ type: "append", key: "cc_chest_circumference" }],
  comparison_linear_density: [{ type: "append", key: "cc_linear_density" }],
  35: {
    comparison_weight: [{ type: "append", key: "cc_bearing" }]
  },

  comparison_width: [{ type: "append", key: "cc_width" }],
  comparison_voltage: [{ type: "append", key: "cc_voltage" }],
  42: {
    hs_code_ru: [
      { type: "append", key: "hs_code_ru", msgRules: { min: 10, max: 10, message: proxy.$t('goods_tariff.verify_tariff_code'), trigger: "blur" } }
    ],
    hs_code_cn: [
      { type: "push", key: "hs_code_cn", msgRules: { min: 10, max: 10, message: proxy.$t('goods_tariff.verify_tariff_code'), trigger: "blur" } }
    ]
  }
};

//input Number验证
const formatChecks = (val, key) => {
  let floatNum = formatObj[key].float,
    intNum = formatObj[key].integer;
  // 小数正则
  const decimal: string = floatNum ? `(\\.\\d{0,${floatNum}})?` : "";
  // 整数正则
  const integer: string = intNum ? `(0|[1-9]\\d{0,${intNum - 1}})` : "\\d*";
  const regExp: RegExp = new RegExp(integer + decimal, "g");

  tariffForm.value[key] =
    val
      .toString()
      .trim()
      .replace(/[^\d.]/g, "")
      ?.match?.(regExp)?.[0] ?? "";

  //先判断类型在判断key
  if (validObjs[props.typeId]) {
    console.log(validObjs[props.typeId][key])
    addRules(validObjs[props.typeId][key]);
  } else {
    addRules(validObjs[key]);
  }
  removeRuls(); //输入移除部分验证
};

//select change 验证key
const validKeys = (val, key) => {
  //先判断类型在判断key
  if (validObjs[props.typeId]) {
    addRules(validObjs[props.typeId][key]);
  } else {
    addRules(validObjs[key]);
  }

  removeRuls(); //输入移除部分验证
};
//根据类型校验必填项
const getTypeRequire = type => {
  console.log(tariffForm.value);

  // 从价税率-RU或从量税率-RU必须填写一个
  //3 毛巾  9 床品
  // 4 服装(非毛皮) 12 服装(毛皮)
  // 15 地垫 34 推车  35 童车 40儿童家具  41游戏娱乐
  // 17内裤 18袜子 27围巾 59 帽子
  //29 节日用品  36 成人水杯
  //19 母婴用品 20洗护用品 21 妈妈用品 22 母婴用品
  //23 包装物
  //26 个人护理
  //30 滤清器 31 发动机配件 32 制动系统 33 悬架系统
  if (
    [
      "3",
      "9",
      "4",
      "12",
      "15",
      "34",
      "35",
      "40",
      "41",
      "29",
      "36",
      "17",
      "18",
      "27",
      "59",
      "19",
      "20",
      "21",
      "22",
      "23",
      "26",
      "30",
      "31",
      "32",
      "33"
    ].includes(props.typeId)
  ) {
    let msgRule = { required: true, message: proxy.$t('goods_tariff.verify_tax_rate'), trigger: "blur" };
    if (!tariffForm.value?.ad_valorem_tax && !tariffForm.value?.specific_duty) {
      let rules = [
        { type: "append", key: "ad_valorem_tax", msgRules: msgRule },
        { type: "append", key: "specific_duty", msgRules: msgRule }
      ];
      addRules(rules, type);
    }
  }
  // 清关里料或清关面料必须填写一个
  //  12 服装(毛皮)
  if (["12"].includes(props.typeId)) {
    let msgRule = { required: true, message:proxy.$t('goods_tariff.cc_material_lining_or_cc_material_plus_required'), trigger: "change" };
    if (!tariffForm.value?.cc_material_lining && !tariffForm.value?.cc_material_plus) {
      let rules = [
        { type: "append", key: "cc_material_lining", msgRules: msgRule },
        { type: "append", key: "cc_material_plus", msgRules: msgRule }
      ];
      addRules(rules, type);
    }
  }
};

const removeRuls = () => {
  //3 毛巾  9 床品
  //  4 服装(非毛皮) 12 服装(毛皮)
  // 15 地垫   34 推车  35 童车 40儿童家具 41游戏娱乐
  //17内裤 18袜子 27围巾 59帽子
  //29节日用品  36成人水杯
  //19 母婴用品 20洗护用品 21 妈妈用品 22 母婴用品
  //23 包装物
  //26 个人护理
  //30 滤清器 31 发动机配件 32 制动系统 33 悬架系统
  //价税率-RU或从量税率-RU
  if (
    [
      "3",
      "9",
      "4",
      "12",
      "15",
      "34",
      "35",
      "40",
      "41",
      "17",
      "29",
      "36",
      "18",
      "27",
      "59",
      "19",
      "20",
      "21",
      "22",
      "23",
      "26",
      "30",
      "31",
      "32",
      "33"
    ].includes(props.typeId)
  ) {
    if (tariffForm.value?.ad_valorem_tax || tariffForm.value?.specific_duty) {
      if (tariffRules.value.ad_valorem_tax) {
        delete tariffRules.value.ad_valorem_tax;
        tariffRef.value?.clearValidate("ad_valorem_tax");
      }

      if (tariffRules.value.specific_duty) {
        delete tariffRules.value.specific_duty;
        tariffRef.value?.clearValidate("specific_duty");
      }
    }
  }
  //清关里料或清关面料
  if (["12"].includes(props.typeId)) {
    if (tariffForm.value?.cc_material_lining || tariffForm.value?.cc_material_plus) {
      if (tariffRules.value.cc_material_lining) {
        delete tariffRules.value.cc_material_lining;
        tariffRef.value?.clearValidate("cc_material_lining");
      }

      if (tariffRules.value.cc_material_plus) {
        delete tariffRules.value.cc_material_plus;
        tariffRef.value?.clearValidate("cc_material_plus");
      }
    }
  }
};

const addRules = (paramsRuls, type) => {
  if (paramsRuls && paramsRuls.length) {
    paramsRuls.map(rulsItem => {
      console.log(rulsItem);
      if (rulsItem.type == "push") {
        // let msgObjRuls = JSON.parse(rulsItem.msgRules);
        console.log(rulsItem.msgRules);
        tariffRules.value[rulsItem.key].push(rulsItem.msgRules);
        console.log(tariffRules.value);
      } else {
        if (!tariffRules.value[rulsItem.key]) {
          if (rulsItem.msgRules) {
            // let msgObjRuls = JSON.parse(rulsItem.msgRules);
            let arrRuls = [];
            arrRuls.push(rulsItem.msgRules);
            tariffRules.value[rulsItem.key] = arrRuls;
          } else {
            tariffRules.value[rulsItem.key] = [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }];
          }
        }
      }
    });
    if (type != "submit") {
      setTimeout(() => {
        tariffRef.value?.clearValidate();
      }, 30);
    }
  }
};
//#endregion

//初始化加载接口
const initForm = () => {
  let paramsObj = { type_id: props.typeId };
  if (props.editId) {
    paramsObj.id = props.editId;
  }
  getTariffFormApi(paramsObj).then(res => {
    console.log(res);
    let { code, data } = res;
    if (code == ResultEnum.SUCCESS) {
      if (data && data.length) {
        let formObj = {},
          formRules = {};
        data.map(fItem => {
          formObj[fItem.key] = fItem.value;
          if (fItem.require) {
            if (fItem.type == "select") {
              formRules[fItem.key] = [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }];
            }
            if (fItem.type == "input") {
              formRules[fItem.key] = [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }];
            }
            if (fItem.type == "number") {
              formRules[fItem.key] = [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }];
            }
          }
        });

        handleData(data);
        formData.value = data;
        tariffRules.value = formRules;
        tariffForm.value = formObj; //表单
        tariffRef.value?.resetFields();
        tariffLoading.value = false;
      }
    } else {
      tariffLoading.value = false;
    }
  });
};

const handleData = data => {
  let constArr = ["1"]; //合并input+select
  // if(["1"].includes(props.typeId))
};
onMounted(() => {});
const $emit = defineEmits<{
  drawerClose: any;
  saveSuccess: any; //保存成功
}>();
</script>
<style lang="scss" scoped></style>
